$(document).ready(function () {
    var customAuthType = 'CUSTOM';

    var form = $('#form');

    var authType = $('#auth-type');
    var username = $('#username');
    var password = $('#password');

    var credentials = $('#credentials');

    var projectShortName = $('#project-short-name');

    var name = $('#name');
    var shortName = $('#short-name');
    var baseUrl = $('#base-url');

    var testUrlButton = $('#test-url-button');

    var askUserModal = $('#ask-user-modal');
    var addTaskButton = $('#add-task-button');
    var modalDismissButtons = $('#modal-dismiss-button, #ask-user-modal button.close');

    // setup credentials type select
    authType.change(function () {
        if (authType.val() == customAuthType) {
            credentials.show();
        } else {
            credentials.hide();
        }
    });
    authType.change();

    // set up validation rules
    var selectiveValidator = function (element) {
        if (element.name != 'authType') {
            validator(element);
        }
    };
    var formValidator = form.validate({
        onkeyup: selectiveValidator,
        onfocusout: selectiveValidator,
        rules: {
            name: {
                required: true,
                maxlength: 64
            },
            shortName: {
                required: true,
                maxlength: 32,
                pattern: shortNamePattern
            },
            baseUrl: {
                required: true,
                maxlength: 255,
                svnUrl: true
            }
        },
        errorPlacement: function (error, element) {
            if (element.attr('name') == 'baseUrl') {
                testUrlButton.disable();
            }
            errorPlacer(error, element);
        },
        highlight: highlighter,
        unhighlight: function (element) {
            if (['authType', 'username', 'password'].indexOf(element.name) < 0) {
                unhighlighter(element);
            }
        },
        success: function (element) {
            if ($(element).attr('for') == 'base-url') {
                testUrlButton.enable();
            }
        },
        submitHandler: function () {
            $.ajax(projectShortName.length > 0 ? getEditProjectSubmitter() : getCreateProjectSubmitter());
        }
    });

    // assign conditional validation rules
    var nameRemoteValidationRule = {remote: _context + '?is-name-available'};
    name.focusout(function () {
        if (!name.isInitialValueSet()) {
            name.rules('add', nameRemoteValidationRule);
        }

        if (shortName.isBlank()) {
            setShortNameFromName();
        }
    });
    name.focusin(function () {
        name.rules('remove', 'remote');
    });

    var shortNameRemoteValidationRule = {remote: _context + '?is-short-name-available'};
    shortName.focusout(function () {
        if (!shortName.isInitialValueSet()) {
            shortName.rules('add', shortNameRemoteValidationRule);
        }
    });
    shortName.focusin(function () {
        shortName.rules('remove', 'remote');
    });

    baseUrl.focusout(function () {
        if (name.isBlank() && formValidator.check(baseUrl)) {
            name.val(baseUrl.getLastUrlToken());
        }
    });

    // modal dismiss button
    modalDismissButtons.click(function (evt) {
        evt.preventDefault();
        location.reload();
    });


    // test url button
    var baseUrlLabel = $('label[for=base-url].help-inline');
    var indicator = $('#indicator');
    testUrlButton.click(function () {
        baseUrlLabel.text('');
        baseUrl.closest('.control-group').removeClass('error');
        testUrlButton.attr('disabled', 'true');
        indicator.show();
        $.ajax({
            url: _context + '?test-url',
            method: 'post',
            dataType: 'json',
            contentType: 'application/json',
            data: JSON.stringify({
                url: baseUrl.val(),
                authType: authType.val(),
                username: getUsername(),
                password: getPassword()
            }),
            success: function (response) {
                if (response.valid) {
                    baseUrl.closest('.control-group').removeClass('error').addClass('success');
                    baseUrlLabel.text('Success!');
                } else {
                    $.each(response.violations, function(key, value) {
                        value.property = 'vcsAttributes.url';
                    });
                    handleViolations(response);
                }

                indicator.hide();
                testUrlButton.enable();
            },
            error: function () {
                alert("Internal error");
                indicator.hide();
                testUrlButton.enable();
            }
        });
    });

    if (!formValidator.check(baseUrl)) {
        testUrlButton.disable();
    }

    // functions
    function getUsername() {
        return authType.val() == customAuthType ? username.val() : null;
    }

    function getPassword() {
        return authType.val() == customAuthType ? password.val() : null;
    }

    function getCreateProjectSubmitter() {
        return {
            url: '?create',
            async: false,
            type: 'post',
            dataType: 'json',
            contentType: 'application/json',
            data: getProjectData(),
            success: function (response) {
                if (response.valid) {
                    addTaskButton.click(function () {
                        window.location.href = _context + response.data + '?new-task';
                    });
                    modalDismissButtons.click(function () {
                        window.location.href = _context + response.data;
                    });
                    askUserModal.modal();
                } else {
                    handleViolations(response);
                }
            },
            error: function () {
                alert('Project was not saved due to internal error');
            }
        };
    }

    function getEditProjectSubmitter() {
        return {
            url: _context + projectShortName.val() + '?apply',
            async: false,
            type: 'post',
            dataType: 'json',
            contentType: 'application/json',
            data: getProjectData(),
            success: function (response) {
                if (response.valid) {
                    window.location.href = _context + response.data;
                } else {
                    handleViolations(response);
                }
            },
            error: function () {
                alert('Project was not saved due to internal error');
            }
        };
    }

    function getProjectData() {
        return JSON.stringify({
            name: name.val(),
            shortName: shortName.val(),
            vcsAttributes: {
                url: baseUrl.val(),
                authType: authType.val(),
                username: getUsername(),
                password: getPassword()
            }
        });
    }

    function setShortNameFromName() {
        shortName.val(name.val()
            .replace(preReplaceRegExp, '__')
            .replace(replaceRegExp, '_'));
        shortName.valid();
    }
});